﻿using System.Windows;
using GalaSoft.MvvmLight.Messaging;
using SessionHunter.Business.Exceptions;
using SessionHunter.Messages;

namespace SessionHunter.Views
{
    /// <summary>
    /// Allows the user to enter a new or change the existing connection string 
    /// </summary>
    public partial class ChangeDatabaseConnectionView : Window
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// Initializes a new instance of the ChangeDatabaseConnectionView class.
        /// </summary>
        public ChangeDatabaseConnectionView()
        {
            InitializeComponent();
            Messenger.Default.Register<ChangeDatabaseConnectionMessage>(this, NotificationMessageReceived);

            // To be able to show messageboxes
            Messenger.Default.Register<DialogMessage>(
                this,
                msg =>
                {
                    var result = MessageBox.Show(
                        msg.Content,
                        msg.Caption,
                        msg.Button);

                    // Send callback
                    msg.ProcessCallback(result);
                });
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Window.Closed"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnClosed(System.EventArgs e)
        {
            Messenger.Default.Unregister<ChangeDatabaseConnectionMessage>(this);
            Messenger.Default.Unregister<DialogMessage>(this);
            base.OnClosed(e);
        }

        /// <summary>
        /// When a message is received, it is processed by this method
        /// </summary>
        /// <param name="msg">The message received.</param>
        protected void NotificationMessageReceived(ChangeDatabaseConnectionMessage msg)
        {
            logger.Info("ChangeDatabaseConnectionView received message {0}", msg.Message.ToString());

            switch (msg.Message)
            {
                case ChangeDatabaseConnectionMessage.MessageAction.CloseChangeDatabaseConnectionDialog:
                    this.DialogResult = true;
                    break;
                default:
                    throw new UnhandledCaseException(msg.Message);
            }
        }
    }
}